<template>
    <d2-container>

        <el-dialog
                title="导出报表"
                :visible.sync="showExcel"
                width="400px">
            <el-form :inline="true"  >
                <el-form-item>
                    开始日期：
                <el-date-picker
                        v-model="start_time"
                        type="date"
                        placeholder="选择日期时间"
                        style='width: 150px'
                        >
                </el-date-picker>
            </el-form-item>

            <el-form-item >
                结束日期：
                <el-date-picker
                        v-model="end_time"
                        type="date"
                        placeholder="选择日期时间"
                        style='width:150px'
                        >
                </el-date-picker>
            </el-form-item>
            
                    
            </el-form>
            
            <div style="width: 100%;text-align: right">
            <el-button @click="showExcel = false">
                取消
            </el-button>
            <el-button @click="exportExcel" type='primary'>
                导出
            </el-button>
        </div>
            
        </el-dialog> 

        <el-dialog title="备注信息" :visible.sync="showMemo">

                        <el-input placeholder="备注" v-model="memo" size="small" :disabled='true' type='textarea' :rows=10  style='white-space: pre-line;'>
                            
                        </el-input>

                        
                        <div slot="footer" class="dialog-footer">
                            <el-button type="primary" @click="showMemo = false">确认</el-button>
                        </div>
         </el-dialog>


        <el-dialog title="回复备注信息" :visible.sync="showNewMemo">

                        <el-input placeholder="备注" v-model="newMemo" size="small"  type='textarea' :rows=10  style='white-space: pre-line;'>
                            
                        </el-input>

                        
                        <div slot="footer" class="dialog-footer" style="float:right;margin-left: 10px">
                            <el-button type="primary" @click="confirmRequest">确认</el-button>
                        </div>
                        <div slot="footer" class="dialog-footer" style="margin-right: 10px">
                            <el-button type="secondary" @click="cancelRequest">取消</el-button>
                        </div>
         </el-dialog>


                     <el-dialog
                title="采购请求详情"
                :visible.sync="dialogVisible2"
                width="1000px" height='300px'>

                <div id="printMe" style="width: 910.8px;height:258px;border:solid 1px black;position: relative;">
                    <div>
                    <div style="font-size:30px;font-weight: 10px;text-align: center;border-bottom: solid 1px #cccccc;width: 100%;display: block">{{request.school.name}}采购配货单</div>
                    <div style="font-size:18px;font-weight: 5px;width: 33%;border-bottom: solid 1px #cccccc;display: inline-block;border-right:solid 1px #cccccc"><span>申购校区:{{request.toSchool.name}}</span></div>
                     <div style="font-size:18px;font-weight: 5px;width: 33%;border-bottom: solid 1px #cccccc;display: inline-block;border-right:solid 1px #cccccc;color:white"><span>1</span></div>
                    <div style="font-size:18px;font-weight: 5px;width: 33%;border-bottom: solid 1px #cccccc;display: inline-block;"><span>日期:{{request.dateOG}}</span></div> 

                    <table style="width: 100%;border-collapse: collapse;display: block" >
                            <tr style="font-size: 18px;width: 100%;">
                                <th style="width: 36%;border-right:solid 1px black;border-bottom: solid 1px black;padding:0">项目</th>
                                <th style="width: 15%;border-right:solid 1px black;border-bottom: solid 1px black">数量</th>
                                <th style="width: 15%;border-right:solid 1px black;border-bottom: solid 1px black">单价(元)</th>
                                <th style="width: 11%;border-right:solid 1px black;border-bottom: solid 1px black">合计金额(元)</th>
                                <th style="width: 11%;border-right:solid 1px black;border-bottom: solid 1px black">优惠金额(元)</th>
                                <th style="width: 11%;border-bottom: solid 1px black">实收金额(元)</th>
                            </tr>
                            <tr v-for='item in request.productOrder' style="margin-bottom: 3px;font-size: 12px">
                                <td style="text-align: center;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;border-right:solid 1px black;border-bottom: solid 1px black">{{item.product.name}}</td>
                                <td style="text-align: center;border-right:solid 1px black;border-bottom: solid 1px black;">{{item.amount}}</td>
                                <td style="text-align: center;border-right:solid 1px black;border-bottom: solid 1px black;">{{item.product.wholeSalePrice}}</td>
                                <td style="text-align: center;border-right:solid 1px black;border-bottom: solid 1px black;" v-if='item.amount != undefined'>{{parseFloat(item.product.wholeSalePrice * item.amount).toFixed(2)}}</td>
                                <td style="text-align: center;border-right:solid 1px black;border-bottom: solid 1px black;" v-if='item.amount != undefined'>0</td>
                                <td style="text-align: center;border-bottom: solid 1px black;" v-if='item.amount != undefined'>{{parseFloat(item.product.wholeSalePrice * item.amount).toFixed(2)}}</td>
                                <td style="text-align: center;border-right:solid 1px black;border-bottom: solid 1px black;color:white" v-if='item.amount == undefined'>-</td>
                                <td style="text-align: center;border-right:solid 1px black;border-bottom: solid 1px black;color:white" v-if='item.amount == undefined'>-</td>
                                <td style="text-align: center;border-bottom: solid 1px black;color:white" v-if='item.amount == undefined'>-</td>
                            </tr>
                            
                        </table>
                        <div  style="font-size:18px;font-weight: 5px;width: 100%;text-align: left;border-bottom: solid 1px black;">合计:{{request.total}}元</div>
                        <div  style="font-size:16px;font-weight: 5px;width: 50%;text-align: left;display: inline-block;">支付状态:{{request.payStatusText}}</div>

                        <div  style="font-size:16px;font-weight: 5px;width: 50%;text-align: left;display: inline-block;">支付方式:{{request.payWayText}}</div>
                        
                         <div  style="font-size:16px;font-weight: 5px;width: 100%;text-align: left;border-bottom: solid 1px black;text-overflow: ellipsis;white-space: nowrap;overflow: hidden;">备注:{{request.memo}}</div>


                         <div  style="font-size:16px;font-weight: 5px;width: 33%;text-align: left;display: inline-block;border-right: solid 1px #cccccc;">采购人:{{request.staff.name}}</div>
                         <div  style="font-size:16px;font-weight: 5px;width: 33%;text-align: left;display: inline-block;border-right: solid 1px #cccccc;">配货人:{{request.mainStaff.name}}</div>
                         <div  style="font-size:16px;font-weight: 5px;width: 33%;text-align: left;display: inline-block;">配货单位（章）</div>
                     </div>
                </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click='printabc("div")'>打印订单</el-button>
                <el-button type="primary" @click="dialogVisible2 = false">关闭</el-button>
            </span>
        </el-dialog>

        <el-form :inline="true" :model="dataSearch" ref="dataSearch">
            
            <el-form-item style="float:right">
                <a href="#/product-request-new">
                    <el-button type="primary"  icon="el-icon-plus">采购请求</el-button>
                </a>
            </el-form-item>
             <el-form-item style='float: right'>
                    <el-button type="primary" style="float:right" @click='showExcel = true'>导出记录</el-button>

            </el-form-item>
        </el-form>

        <el-table :data="dataList" border style="width: 100%">
            <el-table-column  label="商品名称">
                 <template  slot-scope='scope'>
                   <div style="white-space: pre-line;">  {{scope.row.productText}}</div>
                </template>
            </el-table-column>
            <el-table-column prop="toSchool.name" label="请求校区"></el-table-column>
            <el-table-column prop="school.name" label="出售校区"></el-table-column>

            <!--      <el-table-column prop="price" label="金额"></el-table-column>-->
            <el-table-column prop="total" label="总价(元)"></el-table-column>
            <el-table-column prop="statusText" label="状态"></el-table-column>
            <el-table-column prop="payStatusText" label="付款状态"></el-table-column>
            <el-table-column prop="date" label="最后操作时间"></el-table-column>
                  <el-table-column fixed="right" label="操作">
                    <template slot-scope="scope">
                        <div style="display: block">
                     <el-button @click="detailClick(scope.row)" type="text" size="small">查看详情</el-button>
                     <el-button @click="handleClick(scope.row)" type="text" size="small">查看备注</el-button>
                 </div>
                      <el-button @click="accept(scope.$index)" type="text" size="small" v-if='(scope.row.status == 0) && (scope.row.inSchool)'>同意</el-button>
                      <el-button @click="decline(scope.$index)" type="text" size="small" v-if='(scope.row.status == 0) && (scope.row.inSchool)'>拒绝</el-button>
                      <el-button @click="confirmShipping(scope.$index)" type="text" size="small" v-if='(scope.row.status == 1) && (scope.row.inSchool)'>确认发货</el-button>
                      <el-button @click="confirmReceive(scope.$index)" type="text" size="small" v-if='(scope.row.status == 2) && (scope.row.buySchool)'>确认收货</el-button>
                    <el-button @click="confirmPay(scope.$index)" type="text" size="small" v-if='(scope.row.payStatus == 0) && (scope.row.inSchool) && (scope.row.status > 0)'>确认收款</el-button>
                    </template>
                  </el-table-column>
        </el-table>
        <el-pagination
                background
                layout="total,sizes,prev, pager, next,jumper"
                :page-size="pageSize"
                :current-page="currentPage"
                :total="total"
                @current-change="handleCurrentChange"
                @size-change="handlerSizeChange"
                @next-click="handleNextPage"
                @prev-click="handlePrevClick"
        ></el-pagination>
    </d2-container>
</template>

<script>

    

    import request from "@/plugin/axios";
    import {mapState} from "vuex";
        import formatTime from '@/libs/util.formatTime.js'
                import excel from "@/libs/util.excel"


    export default {
        data() {
            return {

                total: 0,
                pageSize: 20,
                currentPage: 1,
                dataList : [],
                dataSearch: {
                    staff: "",
                    student: "",
                    status: "",
                    name:""
                },
                refund_id: undefined,
                dialogVisible: false,
                stock_refund: undefined,
                refund_school: undefined,
                school: undefined,
                memo : '',
                showMemo :false,
                status : -1,
                newMemo : '',
                showNewMemo : false,
                index : -1,
                dialogVisible2 : false,
                showExcel : false,
                start_time : undefined,
                end_time : undefined,
                request : {
                    school : {},
                    toSchool :{},
                    productOrder:[],
                    staff:{},
                    mainStaff :{}
                }
            };
        },
        computed: {
            ...mapState('d2admin/user', ['info']),
        },
        methods: {
            printabc(div){
            var PW =  window.open('', '', 'left=0,top=0,width=600,height=848.6,toolbar=0,scrollbars=0,status=0');
            // 获取div中的html内容
            PW.document.write(document.getElementById('printMe').innerHTML);
            PW.document.close();
            PW.focus();
            PW.print();
            PW.close();

            return false;

    },
            handleClick(row){
                this.memo = row.memo
                this.showMemo = true
            },
            detailClick(row){
                console.log(row)
                this.request = row
                if (this.request.productOrder.length < 5){
                    this.request.productOrder.push({product:{},amount:undefined,total:undefined})
                }
                this.dialogVisible2 = true
            },

            accept(row){
                this.showNewMemo = true
                this.status = 0
                this.index = row
            },
            decline(row){
                this.showNewMemo = true
                this.status = -1
                this.index = row
            },
            confirmShipping(row){
                this.showNewMemo = true
                this.status = 1
                this.index = row
            },
            confirmReceive(row){
                this.showNewMemo = true
                this.status = 2
                this.index = row
            },

            confirmPay(row){
                this.$confirm('','确认收款吗？',{
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(()=>{
                    request({
                    url: "/productOrder/updateRequestPayStatus",
                    method: "post",
                    data : {id : this.dataList[row]._id}
                }).then(res => {
                    this.$alert('','确认成功！')
                    this.getRequestList(this.currentPage,this.pageSize)
                })
                 })

            },

            confirmRequest(){
                let message = ''
                let message2 = ''
                if (this.status == 0){
                    message = '确定确认来自' + this.dataList[this.index].toSchool.name + '采购请求吗？'
                }
                if (this.status == -1){
                    message = '确定拒绝来自' + this.dataList[this.index].toSchool.name + '采购请求吗？'
                }
                if (this.status == 1){
                    message = '确定发货给' + this.dataList[this.index].toSchool.name + '吗？'
                    message2 = '确认后，库存会自动调整'
                }
                if (this.status == 2){
                    message = '确定收到来自' + this.dataList[this.index].toSchool.name + '的教材货物吗？'
                    message2 = '确认后，库存会自动调整,如果商品列表里，没有同样名字的商品会自动创建。'
                }
                this.$confirm(message2,message,{
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(()=>{
                    let url = '/productOrder/productRequestAccept'
                    if (this.status == -1){
                        url = '/productOrder/productRequestReject'
                    }
                    else if (this.status == 1){
                        url = '/productOrder/productRequestConfirmShipping'
                    }
                    else if (this.status == 2){
                        url = '/productOrder/productRequestConfirmReceive'
                    }

                    request({
                    url: url,
                    method: "post",
                    data : {id : this.dataList[this.index]._id,newMemo:this.newMemo,staff:this.staff,school:this.school}
                    }).then(res => {
                        console.log('bbb')
                        this.$alert('','确认成功！')
                        this.showNewMemo = false
                        this.newMemo = ''
                        this.index = -1
                        this.status = - 1
                        this.getRequestList(this.currentPage,this.pageSize)
                    })


                })
            },

            cancelRequest(){
                this.newMemo = ''
                this.showNewMemo = false
                this.status = -1
                this.index = -1
            },

            formSubmit() {
                this.getStockList(1, this.pageSize);
            },
            formReset() {
                this.$refs.dataSearch.resetFields();
            },

            handleCurrentChange(e) {
                this.getStockList(e, this.pageSize);
            },
            handlerSizeChange(e) {
                this.pageSize = e;
                this.getStockList(1, this.pageSize);
            },
            handleNextPage(e) {
                this.getStockList(e, this.pageSize);
            },
            handlePrevClick(e) {
                this.getStockList(e, this.pageSize);
            },

            exportExcel(){
                let data = {}
                if (new Date(this.start_time) >new Date(this.end_time)){
                    this.$message('开始时间不能大于结束时间')
                    return false
                }
                data.start_time = this.start_time
                data.end_time = this.end_time
                data.school = this.school
                // data.headquarter = this.headquarter ? 1 : undefined
                request({
                    url: "/productOrder/exportRequest",
                    method: "post",
                    data: data
                }).then(res => {
                   if (res.code == 200){
                        let temp = []
                        let merge = []
                        let columns = res.data.columns
                        temp.push(columns.map(function(e){return e.label}))
                        let key = columns.map(e=> e.prop)
                        for (var i =0 ; i < res.data.data.length ; i++){
                            let ak = {}
                            for (var j = 0 ; j < res.data.data[i].productOrder.length ; j++){
                                let os = res.data.data[i]
                                ak.date = formatTime.formatDate(new Date(os.createdAt))
                                ak.product = os.productOrder[j].product.name
                                ak.amount = os.productOrder[j].amount
                                ak.wholeSalePrice = os.productOrder[j].product.wholeSalePrice
                                ak.total = parseFloat(ak.amount * ak.wholeSalePrice).toFixed(2)
                                ak.toSchool = os.toSchool == null ? '未知' : os.toSchool.name
                                ak.school = os.school == null ? '未知' : os.school.name

                                if (os.status == 0){
                                    ak.type = '初次请求'
                                    ak.next = '确认或拒绝请求'
                                }
                                else if (os.status == 1){
                                    ak.type = '接受请求，等待下一步操作'
                                    ak.next = '等待请求方打款'
                                    if (ak.toSchool != null){
                                        if (ak.toSchool._id == this.school){
                                            ak.next = '请打款'
                                        }
                                    }
                                }
                                else if (os.status == -1){
                                    ak.type = '已拒绝'
                                    ak.next = ''
                                    if (ak.toSchool._id == this.school){
                                            ak.next = '请查看备注下一步操作'
                                        }
                                }
                                else if (os.status == 2){
                                    ak.type = '已发货'
                                    ak.next = '等待请求方确认收货完成交易'
                                    if (ak.toSchool._id == this.school){
                                            ak.next = '请确认收货完成交易'
                                        }
                                }
                                else if (os.status == 3){
                                    ak.type = '确认到货，交易完成'
                                    ak.next = '交易完成'
                                }
                                ak.payStatus = ak.payStatus == 0 ? '未付款' : '已付款'
                                let newData = []
                                key.forEach(value2 =>{
                                    newData.push(ak[value2])
                                })
                                temp.push(newData)
                            }
                            if (res.data.data[i].productOrder.length >1){
                                    let srow = temp.length - res.data.data[i].productOrder.length 
                                    let erow = temp.length - 1
                                    merge.push( { s: { r: srow, c: 0 }, e: { r: erow, c: 0 } })
                                    merge.push( { s: { r: srow, c: 5 }, e: { r: erow, c: 5 } })
                                    merge.push( { s: { r: srow, c: 6 }, e: { r: erow, c: 6 } })
                                    merge.push( { s: { r: srow, c: 7 }, e: { r: erow, c: 7 } })
                                    merge.push( { s: { r: srow, c: 8 }, e: { r: erow, c: 8 } })
                                    merge.push( { s: { r: srow, c: 9 }, e: { r: erow, c: 9 } })
                            }
                           temp.push(['','','','','','','','','','','',''])


                        }
                        let width = []
                        for (var i =0 ; i < temp[0].length - 1;i++){
                            width.push({wch:10})
                            if (i == 7){
                                width[i].wch = 20
                            }
                        }
                        width.push({wch:20})
                        excel.exportRaw(temp,'采购请求表',merge,width)
                   }
                });

            },

            getRequestList(page, pageSize) {
                let data = this.dataSearch;
                (data.page = page), (data.pageSize = pageSize);
                data.school = this.school;
             

                request({
                    url: "/productOrder/getProductRequestList",
                    method: "post",
                    data
                }).then(res => {
                    // console.log(res)
                    let temp = []
                    for (var i = 0 ; i < res.data.list.length ; i ++){
                        let a = res.data.list[i]
                        a.payStatusText = a.payStatus == 0 ? '未支付' : '已支付'
                        if (a.payWay == 0){
                            a.payWayText = '现金'
                        }
                        else if (a.payWay == 1){
                            a.payWayText = '银行卡'
                        }
                        else if (a.payWay == 3){
                            a.payWayText = '微信'
                        }
                        else if (a.payWay == 2){
                            a.payWayText = '支付宝'
                        }
                        let inSchool = this.school == res.data.list[i].school._id
                        let buySchool = this.school == res.data.list[i].toSchool._id
                        a.inSchool = inSchool
                        a.buySchool = buySchool
                        a.dateOG = formatTime.formatTime(new Date(res.data.list[i].createdAt))
                        a.date = formatTime.formatTime(new Date(res.data.list[i].updatedAt || res.data.list[i].createdAt))
                            if (a.status == 0){
                                a.statusText = '未确认'
                            }
                            else if (a.status == 1){
                                a.statusText = '等待确认发货'
                            }
                            else if (a.status == 2){
                                a.statusText = '等待确认收货'
                            }
                            else if (a.status == 3){
                                a.statusText = '已完成'
                            }
                       else if (a.status == -1){
                            a.statusText = '已拒绝'
                        }
                        a.productText = a.productOrder.map(function(e){
                            return e.product.name + ' x ' + e.amount
                        }).join('\n')
                        if (a.staff == undefined){
                                    a.staff = {}
                                }
                                if (a.mainStaff == undefined){
                                    a.mainStaff = {}
                                }
                        temp.push(a)
                    }
                    this.dataList = temp
                    console.log(this.dataList)
                    this.total = res.data.count
                });
            },

           load(){
            this.school = this.info.school[0]._id
             this.staff = this.info.staff == undefined ? null : this.info.staff._id
            this.staffname = this.info.staff == undefined ? '' : this.info.staff.name
            this.start_time = new Date(new Date().getTime() - 3600000 * 24 * 30)
            this.end_time = new Date()
            this.headquarter = this.info.school[0].headquarter == 1 || this.info.school[0].headquarter == 2
            this.getRequestList(1, this.pageSize);
           }
          
        },
        beforeRouteEnter(to,from,next){
            console.log(to.meta.refresh,'reerr')
            if (to.meta.refresh == 'a'){
                to.meta.refresh = undefined
                next(v=>{
                    v.load()
                })
            }
            else{
                next()
            }

        },


        created() {
            this.load()
        }
    };
</script>
